<template>
    <div v-model="editRole">
        <div class="">
            <!--<p class="addRole-p" >您正在设置权限的角色：<span>{{this.addForm.ids}}</span></p>-->
            <!--<p class="addRole-p"><span>快捷链接:</span><span>用户管理</span></p>-->
            <Form ref="addForm" :model="addForm" :rules="ruleValidate" :label-width="80">
                <FormItem label="角色名称:" prop="roleName">
                    <Input type="text" clearable style="width: 240px" placeholder="请输入角色名称" v-model="addForm.roleName"></Input>
                </FormItem>
                <FormItem label="角色状态:" prop="enableStatus">
                    <Select v-model="addForm.enableStatus" clearable style="width:240px">
                        <Option v-for="item in modulesOpt" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="角色类型:" prop="roleType">
                    <Select v-model="addForm.roleType" clearable style="width:240px">
                        <Option v-for="item in modulesOpts" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="选择部门:" prop="orgStructId">
                    <Select v-model="addForm.orgStructId" clearable style="width:240px">
                        <Option v-for="item in modulesOptss" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </FormItem>
                <div style="width: 500px;">
                    <Form-item label="备注" prop="comment">
                        <i-input v-model="addForm.comment" clearable type="textarea" placeholder="请输入..."></i-input>
                    </Form-item>
                </div>
                <div>
                    <div>
                        <Tabs type="card" :animated="false">
                            <Tab-pane label="关联权限">
                                <div class="addRole-box">
                                    <div class="roleTrees" v-model="addForm.menuCodes" style="margin-left: 16px;padding-top: 16px;margin-top: -16px;">
                                        <Tree :data="dataTrees" show-checkbox ref="trees" @on-check-change="treesChanges"></Tree>
                                        <div class="clear" style="clear: both;"></div>
                                    </div>
                                </div>
                            </Tab-pane>
                            <Tab-pane label="事件订阅">
                                <div class="addRole-box">
                                    <div class="eventTree" v-model="addForm.roleEvents" style="margin-left: 30px;padding-top: 16px;margin-top: -16px;">
                                        <Tree :data="dataTree" show-checkbox ref="tree"></Tree>
                                        <div class="clear" style="clear: both;"></div>
                                    </div>
                                </div>
                            </Tab-pane>
                        </Tabs>
                    </div>
                </div>
            </Form>
        </div>
        <div slot="footer">
            <Button type="primary" size="large" @click="saveForm('addForm')" class="margin-top-20">保存设置</Button>
        </div>
    </div>
</template>

<script>
    import { getfunMenuApi ,getEventMenuApi } from '../../http/functionView.api'
    import { updateRoleApi ,addRoleApi ,getRoleTableApi,getOrg_structApi ,copyRoleApi} from '../../http/role.api'
    import _ from "undersocre"
    export default {
        name: 'copyRole',
        props: {
            perInfo: {
                type: Object
            },
            itemOpt: {
                type: Array
            }
        },
        data () {
            return {
                editRole: false,
                spinShow: true,
                dataTrees: [],
                dataTree2: [],
                ruleValidate: {
                    roleName: [
                        { required: true, message: '角色名称不能为空', trigger: 'blur' },
                        { max: 255, message: '最多输入255个字符', trigger: 'blur' }
                    ],
                    enableStatus: [
                        { required: true, message: '角色状态不能为空', trigger: 'blur' }
                    ],
                    roleType: [
                        { required: true, message: '角色类型不能为空', trigger: 'blur' }
                    ],
                    /*orgStructId: [
                        { required: true, message: '选择部门不能为空', trigger: 'blur' }
                    ],*/
                    comment: [
                        { required: true, message: '备注不能为空', trigger: 'blur' },
                        { max: 255, message: '最多输入255个字符', trigger: 'blur' }
                    ]
                },
                formItem: {
                    input: '',
                    select: '',
                    radio: 'male',
                    checkbox: [],
                    switch: true,
                    date: '',
                    time: '',
                    slider: [20, 50],
                    textarea: ''
                },
                addModal: false,
                modulesOpt: [
                    {
                        value: 'true',
                        label: '启用'
                    },
                    {
                        value: 'false',
                        label: '禁用'
                    }
                ],
                modulesOpts: [
                    {
                        value: 'general',
                        label: '普通角色'
                    },
                    {
                        value: 'system',
                        label: '系统角色'
                    }
                ],
                modulesOptss: [],
                addForm: {
                    roleName: '',
                    enableStatus: '',
                    roleType: '',
                    orgStructId: '',
                    comment: '',
                    menuCodes: [],
                    roleEvents: []

                }
            }
        },
        created () {
            const _this = this;
            Promise.all([getRoleTableApi(this.$route.params.id), getfunMenuApi(), getEventMenuApi()]).then(function (res) {
                const resp = res.map(r => r.data.result)
                // console.log(res)
                if(resp[0].enableStatus === true){
                    resp[0].enableStatus = 'true'
                }else if(resp[0].enableStatus === false) {
                    resp[0].enableStatus = 'false'
                }
                resp[0].ids = resp[0].roleName
                resp[0].roleName = ''
                _this.addForm = resp[0]

                function buildTree(tree) {
                    return {
                        title: tree.name,
                        expand: true,
                        children: tree.menuLists.map((item) => getNode(item))
                    }
                }
                function  getNode(item) {
                    let obj = {
                        title: item.name,
                        expand: true,
                        originVal: item
                    };
                    if (item.menuLists&&item.menuLists.length) { // 菜单权限
                        obj.children = item.menuLists.map((item1) => getNodes(item1)); //getNode(item1)没有二级菜单
                    } else if (item.eventLists&&item.eventLists.length) { // 事件订阅
                        obj.children = item.eventLists.map((item1) => getNodes(item1)); //getNode(item1)没有二级菜单
                    }
                    return obj;
                }
                //有二级菜单
                function  getNodes(item1) {
                    let obj = {
                        title: item1.name,
                        expand: true,
                        originVal: item1
                    };
                    if (item1.menuItems&&item1.menuItems.length) {// 菜单权限
                        obj.children = item1.menuItems.map((item2) => ({title: item2.name+(item2.desc?"（"+item2.desc+"）":""), originVal: item2,checked:_this.addForm.menuCodes?(_this.addForm.menuCodes.find(it => it===item2.code) || false):false}));
                    } else if (item1.eventItems&&item1.eventItems.length) {// 事件订阅
                        obj.children = item1.eventItems.map((item2) => ({title: item2.name, originVal: item2,checked:_this.addForm.roleEvents?(_this.addForm.roleEvents.map((item6) => (item6.eventCode)).find(it => it===item2.code) || false):false}));
                    }
                    return obj;
                }
                _this.dataTrees = resp[1].map(tree => buildTree(tree))
                _this.dataTrees2 = resp[2].eventModules.map((item) => getNode(item))
                _this.spinShow = false
            }).catch(err => {
                /* this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)*/
                this.spinShow = false
            })


            getOrg_structApi().then(suc => {
                // console.log('suc.data.result.===',suc.data.result[0].dept)
                this.modulesOptss = suc.data.result.map(opt => ({ value: opt.id, label: opt.dept}))
            })
        },
        /*watch: {
            editRole: function(val) {
                if (val) {
                    console.log("this.perInfo====" + this.perInfo)
                    this.addForm = JSON.parse(JSON.stringify(this.perInfo))
                }
            }
        },*/
        methods: {
            treesChanges (n) {
                /*console.log(n)*/
                let level3=this.dataTrees[1].children[0].children;
                for(let i=0,len=level3.length;i<len;i++) {
                    let item = level3[i].children;
                    let flag=false;
                    for (let j = 0, lenj = item.length; j < lenj; j++) {
                        let subItem = item[j];
                        if(n && _.findWhere(n,{nodeKey:subItem.nodeKey})){
                            flag=true;
                        }
                    }
                    if(flag){
                        for (let j = 0, lenj = item.length; j < lenj; j++) {
                            let subItem = item[j];

                            if (subItem.originVal && subItem.originVal.open) {
                                let hasView = _.findWhere(n, {nodeKey: subItem.nodeKey});
                                if (!hasView) {
                                    subItem.checked = true;
                                }
                            }
                        }
                    }

                }
            },
            formInit () {
                this.addForm = {
                    roleName: '',
                    enableStatus: '',
                    roleType: '',
                    orgStructId: '',
                    comment: '',
                    menuCodes: [],
                    roleEvents: []
                }
            },
            //子页面的保存
            saveForm (name) {
                this.addForm.menuCodes = this.$refs.trees.getCheckedNodes().filter(item => item&&(!item.children||!item.children.length)).map((item2) => (item2.originVal.code))
                this.addForm.roleEvents = this.$refs.tree.getCheckedNodes().filter(item => item&&(!item.children||!item.children.length)).map((item3) => ({eventCode: item3.originVal.code}))
                /*console.log("this.$refs.Tree.getCheckedNodes().title==="+this.$refs.tree.getCheckedNodes().map((item2) => (console.log("title=="+ item2.title))))
                *//*console.log("this.$refs.tree.getSelectedNodes()==="+this.$refs.tree.getSelectedNodes())*/
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.spinShow = true
                        copyRoleApi(this.addForm).then(suc => {
                            this.addModal = false
                            this.$emit('emitAddPerSuc')
                            this.spinShow = false
                            this.$router.push('/role')
                            this.getPerTable()
                        }).catch(err => {
                            this.$Message.error("错误代码【"+err.data.code+"】，"+err.data.message)
                            this.spinShow = false
                        })
                    }
                })
            }
        }
    }
</script>
<style>
    .addRole-p span{
        display: inline-block;
        margin-left: 20px;
        padding-bottom: 20px;
        cursor: pointer;
        font-size: 14px;
    }
    .addRole-div{
        width:100%;
        padding-bottom: 10px;
        margin-bottom: 15px;
        border-bottom:1px solid #ccc;
    }
    .addRole-box{
        border: 1px solid #ccc;
        border-top: 0;
    }
    .addRole-boxs{
        border: 1px solid #ccc;
        margin-top: 20px;
    }
    .margin-top-20{
        margin-top:20px;
    }
</style>
